package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;
import com.xuanzheng.company.service.impl.UserServiceImpl;
import com.xuanzheng.company.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/updateCompanyProfile")
public class CompanyProfileServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();
    private final CompanyService companyService = new CompanyServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(gson.toJson(result));
            return;
        }

        User currentUser = (User) session.getAttribute("user");
        
        // 验证用户是否是公司负责人
        if (currentUser.getRole() != 1) {
            result.put("success", false);
            result.put("message", "只有公司负责人可以更新公司资料");
            out.print(gson.toJson(result));
            return;
        }

        // 初始化参数变量
        String name = null;
        String gender = null;
        String phone = null;
        String email = null;
        String address = null;
        String companyName = null;
        String companyPhone = null;
        String companyAddress = null;
        
        // 检查Content-Type是否为application/json
        String contentType = request.getContentType();
        boolean isJsonRequest = contentType != null && contentType.contains("application/json");
        
        try {
            if (isJsonRequest) {
                // System.out.println("检测到JSON请求");
                // 从请求体读取JSON数据
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = request.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                
                // 解析JSON数据
                JsonObject jsonData = gson.fromJson(sb.toString(), JsonObject.class);
                
                // 获取JSON参数
                name = jsonData.has("name") ? jsonData.get("name").getAsString() : null;
                gender = jsonData.has("gender") ? jsonData.get("gender").getAsString() : null;
                phone = jsonData.has("phone") ? jsonData.get("phone").getAsString() : null;
                email = jsonData.has("email") ? jsonData.get("email").getAsString() : null;
                address = jsonData.has("address") ? jsonData.get("address").getAsString() : null;
                companyName = jsonData.has("companyName") ? jsonData.get("companyName").getAsString() : null;
                companyPhone = jsonData.has("companyPhone") ? jsonData.get("companyPhone").getAsString() : null;
                companyAddress = jsonData.has("companyAddress") ? jsonData.get("companyAddress").getAsString() : null;
                
                // System.out.println("解析的JSON数据: " + sb.toString());
            } else {
                // System.out.println("检测到表单请求");
                // 获取表单参数
                name = request.getParameter("name");
                gender = request.getParameter("gender");
                phone = request.getParameter("phone");
                email = request.getParameter("email");
                address = request.getParameter("address");
                companyName = request.getParameter("companyName");
                companyPhone = request.getParameter("companyPhone");
                companyAddress = request.getParameter("companyAddress");
            }
            
            // 输出接收到的参数值
            // System.out.println("接收到的参数:");
            // System.out.println("name: " + name);
            // System.out.println("gender: " + gender);
            // System.out.println("phone: " + phone);
            // System.out.println("email: " + email);
            // System.out.println("address: " + address);
            // System.out.println("companyName: " + companyName);
            // System.out.println("companyPhone: " + companyPhone);
            // System.out.println("companyAddress: " + companyAddress);
            
            // 验证必填参数
            if (name == null || name.trim().isEmpty() || gender == null || gender.trim().isEmpty() || 
                phone == null || phone.trim().isEmpty() || companyName == null || companyName.trim().isEmpty()) {
                
                // System.out.println("表单验证失败:");
                // System.out.println("name验证: " + (name != null && !name.trim().isEmpty()));
                // System.out.println("gender验证: " + (gender != null && !gender.trim().isEmpty()));
                // System.out.println("phone验证: " + (phone != null && !phone.trim().isEmpty()));
                // System.out.println("companyName验证: " + (companyName != null && !companyName.trim().isEmpty()));
                
                result.put("success", false);
                result.put("message", "姓名、性别、手机号和公司名称不能为空");
                out.print(gson.toJson(result));
                return;
            }
            
            // 检查手机号是否已被其他用户使用
            User existingUser = userService.findByPhone(phone);
            if (existingUser != null && !existingUser.getId().equals(currentUser.getId())) {
                result.put("success", false);
                result.put("message", "该手机号已被其他用户使用");
                out.print(gson.toJson(result));
                return;
            }
            
            // 获取公司信息
            Company company = companyService.getCompanyByManagerId(currentUser.getId());
            if (company == null) {
                result.put("success", false);
                result.put("message", "未找到公司信息");
                out.print(gson.toJson(result));
                return;
            }
            
            // 更新用户信息
            currentUser.setName(name);
            currentUser.setGender(gender);
            currentUser.setPhone(phone);
            currentUser.setEmail(email != null ? email : "");
            currentUser.setAddress(address != null ? address : "");
            
            // 更新公司信息
            company.setName(companyName);
            company.setPhone(companyPhone != null ? companyPhone : "");
            company.setAddress(companyAddress != null ? companyAddress : "");
            
            // 执行更新操作
            boolean userUpdateSuccess = userService.updateUser(currentUser);
            boolean companyUpdateSuccess = updateCompany(company);
            
            if (userUpdateSuccess && companyUpdateSuccess) {
                // 更新会话中的用户对象
                session.setAttribute("user", currentUser);
                
                // 返回更新后的信息
                Map<String, Object> data = new HashMap<>();
                data.put("user", currentUser);
                data.put("company", company);
                
                result.put("success", true);
                result.put("message", "个人和公司资料更新成功");
                result.put("data", data);
            } else {
                result.put("success", false);
                result.put("message", "资料更新失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "处理请求时出错: " + e.getMessage());
        }

        out.print(gson.toJson(result));
    }
    
    private boolean updateCompany(Company company) {
        // 使用原生SQL更新公司信息，因为CompanyService中没有提供更新公司基本信息的方法
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE company SET name = ?, phone = ?, address = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, company.getName());
            pstmt.setString(2, company.getPhone());
            pstmt.setString(3, company.getAddress());
            pstmt.setString(4, company.getId());

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }
} 